﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Code4Bugs.Utils.Intercomm.Sockets;
using Code4Bugs.Utils.IO.Modbus;
using DataBase.DBmodels;
using DataBase.Utils;
using GreenXi.Help.Dam;
using GreenXi.ViewModel.Utils;
using PressSystem_Can.Help.Can;
using Quartz;
using static PressSystem_Can.Help.Can.Can;

namespace GreenXi.Job
{
    [DisallowConcurrentExecution]
    public class ReceiceJob : IJob
    {
        /// <summary>
        /// 获取用电量 每小时执行一次
        /// </summary>
        /// <returns></returns>
        public static ITrigger GetTrigger()
        {
            return TriggerBuilder.Create().WithCronSchedule("59 * * * * ?")
           .Build();
        }
        unsafe public Task Execute(IJobExecutionContext context)
        {
            //foreach (var item in GlobalVariables.CraftViewList)
            //{
            //    var ip = GlobalVariables.GatewayList.Where(x => x.Id == item.GateWayId).FirstOrDefault().IPSite;
            //    ModBus.GetElectricEnergy(item.NodeId, ip,item.StationNode);
            //    Task.Delay(10);
            //}
            MyDbContext myDbContext = new();
            var today = DateTime.Today; // 获取今天的日期（时间部分为 00:00:00）
            foreach (var item in GlobalVariables.CraftViewList)
            {
                var electricity = myDbContext.Electricity.Where(x => x.CraftId == item.Id&& x.CreateTime.Value.Year == today.Year &&
                x.CreateTime.Value.Month == today.Month &&
                x.CreateTime.Value.Day == today.Day).FirstOrDefault();

                if (electricity == null) {
                    electricity=new DataBase.DBmodels.Electricity();
                    electricity.AllElectricityConsumption = Convert.ToDouble(item.Energy);
                    electricity.ElectricityConsumption = 0;
                    electricity.CreateTime=DateTime.Now;
                    electricity.UpdateTime=DateTime.Now;
                    electricity.CraftId= item.Id;
                    myDbContext.Add(electricity);
                }
                else
                {
                    if (today.Day == 1)
                    {
                       // 如果是1号，找上个月的最后一天
                   
                        var todayStart = new DateTime(today.Year, today.Month, today.Day, 0, 0, 0);
                        var lastDayOfLastMonth = todayStart.AddDays(-1); // 上个月的最后一天
                        var lastMonthStart = new DateTime(lastDayOfLastMonth.Year, lastDayOfLastMonth.Month, lastDayOfLastMonth.Day, 0, 0, 0);
                        var lastMonthEnd = lastDayOfLastMonth.AddDays(1);

                        var electricity3 = myDbContext.Electricity
                            .Where(x => x.CraftId == item.Id
                                && x.CreateTime >= lastMonthStart
                                && x.CreateTime < lastMonthEnd)
                            .OrderByDescending(x => x.CreateTime) // 取最后一天的最后一条记录
                            .FirstOrDefault();
                        
                        if (electricity3 != null && electricity3.AllElectricityConsumption != null)
                        {
                            var Electricity = Convert.ToDouble(item.Energy) - electricity3.AllElectricityConsumption.Value;
                            if (Electricity > 0)
                            {
                                electricity.ElectricityConsumption = Electricity;
                            }

                        }
                        if (item.Energy != 0)
                        {
                            electricity.AllElectricityConsumption = Convert.ToDouble(item.Energy);
                        }

                        electricity.UpdateTime = DateTime.Now;
                        myDbContext.Update(electricity);

                    }
                    else
                    {
                        var electricity2 = myDbContext.Electricity.Where(x => x.CraftId == item.Id && x.CreateTime.Value.Year == today.Year &&
               x.CreateTime.Value.Month == today.Month &&
               x.CreateTime.Value.Day == today.AddDays(-1).Day).FirstOrDefault();
                        if (electricity2 != null && electricity2.AllElectricityConsumption != null)
                        {
                            var Electricity = Convert.ToDouble(item.Energy) - electricity2.AllElectricityConsumption.Value;
                            if (Electricity > 0)
                            {
                                electricity.ElectricityConsumption = Electricity;
                            }

                        }
                        if (item.Energy != 0)
                        {
                            electricity.AllElectricityConsumption = Convert.ToDouble(item.Energy);
                        }

                        electricity.UpdateTime = DateTime.Now;
                        myDbContext.Update(electricity);
                    }
             
                  
                }
                myDbContext.SaveChanges();
            }

            return Task.CompletedTask;
        }
    }
}
